package com.sstudio.robot.demo

import ai.easy.robot.task.ISubTask
import ai.easy.robot.task.ITask
import ai.easy.robot.task.InterruptComingSelector
import ai.easy.robot.task.SubTaskParallelManager
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.widget.TextView
import com.easy.robot.task.BaseIdleTask
import com.easy.robot.task.TaskContext
import org.jetbrains.anko.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

/**
 * 演示任务管理
 */
class TasksMgrActivity : BaseActivity() {

    var txtInfo: TextView? = null

    override fun createView(): View? = UI {
        verticalLayout {
            txtAllNodes = textView("All Nodes1:")

            fun View.myStyle() {
                lparams(wrapContent, wrapContent) {
                    leftMargin = 6
                    rightMargin = 6
                }
            }

            linearLayout {
                button("普通任务") {
                    onClick { addTask() }
                    myStyle()
                }
                //用MainWork
                button("普通任务1") {
                    onClick { addTask1() }
                    myStyle()
                }

                button("不可中断任务") {
                    onClick { addTask(false) }
                    myStyle()
                }
            }

            scrollView {
                txtInfo = textView("")
            }
        }
    }.view

    var k = 0;
    fun addTask(canInt: Boolean = true) {
        val task = MyTask("Task_$k", ::showText)
        app.pool.addNewTask(task, canInterrupted = canInt)
        k++
    }

    fun addTask1(canInt: Boolean = true) {
        val task = MyTask1("Task_$k", ::showText)
        app.pool.addNewTask(task, canInterrupted = canInt)
        k++
    }

    fun showText(str: String) {
        val time = SimpleDateFormat("[hh:mm:ss] ").format(Date(System.currentTimeMillis()))
        runOnUiThread { txtInfo?.text = "${txtInfo?.text}\n$time$str" }
    }

    val myIdleTask = object : BaseIdleTask() {
        override fun onStart(ctx: TaskContext) {
            super.onStart(ctx)
            showText("Idle Start")
        }

        override fun onStop(ctx: TaskContext) {
            showText("Idle Stop")
            super.onStop(ctx)
        }
    }

    // 遇到不可打断的任务是提示用户选择
    val myInterruptAsk = object : InterruptComingSelector() {
        var dlg: DialogInterface? = null
        override fun makeSelection(taskName: String, canResume: Boolean) {
            runOnUiThread {
                dlg = alert(message = "是否打断任务${taskName}？") {
                    positiveButton("强制结束") {
                        it.dismiss()
                        finish(InterruptComingSelector.CHOICE_STOP)
                    }
                    negativeButton("忽略") {
                        it.dismiss()
                        finish(InterruptComingSelector.CHOICE_DO_NOTHING)
                    }
                    //
                    if (canResume) {
                        this.neutralPressed("暂停任务") {
                            it.dismiss()
                            finish(InterruptComingSelector.CHOICE_PAUSE)
                        }
                    }
                }.show()
            }
        }

        override fun onFinishOrCancel() {
            runOnUiThread { dlg?.dismiss() }
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //启动任务池主循环
        thread(start = true, name = "taskpool") {
            //设置基本的属性
            app.pool.idleTask = myIdleTask
            app.pool.logger = { showText(it) }
            app.pool.interruptComingSelector = myInterruptAsk
            app.pool.mainLoop()
        }
    }

    override fun onDestroy() {
        app.pool.endLoop()
        super.onDestroy()
    }


    class MyTask constructor(override val name: String, val tracer: (String) -> Unit = {}) : ITask {
        var taskRunning = true
        override val isAlive: Boolean
            get() = taskRunning

        override fun canResume(): Boolean = true

        override fun onStart(ctx: TaskContext) {
            val queue = ctx.createSubTaskQueue()
            queue.get()?.apply {
                add(MySubTask("Sub1@${name}", tracer))
                add(MySubTask("Sub2@${name}", tracer))
                add(MySubTask("Sub3@${name}", tracer))
                add(MySubTask("Sub4@${name}", tracer))
                //
                start {
                    //设置任务运行结束标志
                    taskRunning = false
                }
                //tracer()
            }
        }

        override fun onStop(ctx: TaskContext) {
            //tracer("")
        }

        override fun onPause(ctx: TaskContext) {
        }

        override fun onResume(ctx: TaskContext) {
        }
    }

    class MySubTask(val name: String = "", val tracer: (String) -> Unit = {}) : ISubTask {
        override fun timeout(): Int = 1500 //1.5 sec

        override fun run(paraMgr: SubTaskParallelManager): Boolean {
            tracer("sub task ${name} start run")
            paraMgr.delayMs(1000)
            return true
        }

        override fun onCancel(isTimeout: Boolean): Boolean {
            tracer("sub task ${name} is ${if (isTimeout) "timeout" else "completed"}")
            return true
        }

    }

    //使用maiwork执行任务
    class MyTask1 constructor(override val name: String, val printor:(String)->Unit={}) : ITask{
        override var isAlive: Boolean = true

        override fun canResume(): Boolean  = true

        override fun onStart(ctx: TaskContext) {
            isAlive = true
            ctx.doMainWork {
                for(x in 1 .. 6) {
                    //通过此函数检测任务是否已暂停
                    suspendMainWorkWhenPaused()
                    //
                    delayMs(1000)
                    printor("trick: $x")
                }
                isAlive = false
            }
        }

        override fun onStop(ctx: TaskContext) {

        }

        //private var running = false
        override fun onPause(ctx: TaskContext) {
            //会导致suspendMainWorkWhenPaused()挂起
            ctx.pauseMainWork()
        }

        override fun onResume(ctx: TaskContext) {
            ctx.resumeMainWork()
        }
    }



    override fun addCustomNodes() {

    }

    override fun initMaiFragment() {

    }
}